package cn.kwq.pcsystem.utils;

import cn.hutool.core.date.DateUtil;
import cn.kwq.pcsystem.common.Result;
import cn.kwq.pcsystem.entity.DepartmentDic;
import cn.kwq.pcsystem.vo.DepartmentDicVO;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kwq
 * @Date: 2023/03/14/17:40
 * @Description:
 */
public class ExcelUtils {

    public static <T> boolean writeExcel(Class<T> myClass, List<T> data, String sheetName, HttpServletResponse response, String fileName) throws IOException {
        try{
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            // 下载文件名
           fileName = URLEncoder.encode(fileName+"_"+ DateUtil.now(), "UTF-8")
                   .replaceAll("\\+", "%20");
           response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), myClass)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet(sheetName)
                    .registerWriteHandler(getStyleStrategy())//字体居中策略
                    .doWrite(data);
            return true;
        }catch (Exception e){
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(Result.error().msg("下载文件失败: "+e.getMessage()).toString());
            e.printStackTrace();
            return false;
        }
    }






    /**
     *  设置表格内容居中显示策略
     * @return
     */
    private static HorizontalCellStyleStrategy getStyleStrategy(){
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        //设置头字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)13);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //设置头居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        // 内容策略
        WriteCellStyle writeCellStyle = new WriteCellStyle();
        // 设置内容水平居中
        writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        return new HorizontalCellStyleStrategy(headWriteCellStyle, writeCellStyle);
    }
}
